package net.pws.oos.web;

import java.util.List;

import net.pws.common.beanutils.BeanUtils;
import net.pws.common.util.StringUtils;
import net.pws.common.jackson.JsonUtils;
import net.pws.common.persistence.EntityManager;
import net.pws.oos.biz.model.Dict;
import net.pws.oos.biz.query.DictFinder;
import net.pws.oos.biz.service.DictService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

public abstract class DictAction {
    
    @Autowired
    protected EntityManager entityManager;
    
    @Autowired
    private DictFinder dictFinder;
    
    @Autowired
    private DictService dictService;
    
    protected abstract String getType();
    
    protected String getJspFolder() {
        return getType().toLowerCase();
    }
    
    @RequestMapping("/list.do")
    public String listPage() {
        return "/dict/" + getJspFolder() + "/list";
    }
    
    @RequestMapping("/edit.do")
    public String editPage(String id) {
        return "/dict/" + getJspFolder() + "/edit";
    }
    
    @RequestMapping("/list.json")
    @ResponseBody
    public Object listDatas() {
        List<Dict> models = dictFinder.listDicts(getType());
        return JsonUtils.succeedMap(models);
    }
    
    @RequestMapping("/detail.json")
    @ResponseBody
    public Object detail(String id) {
        if (StringUtils.isBlank(id)) {
            return JsonUtils.failedMap("错误的参数！");
        }
        
        Dict dict = entityManager.find(Dict.class, id);
        return JsonUtils.succeedMap(dict);
    }
    
    @RequestMapping("/save.json")
    @ResponseBody
    public Object save(Dict dict) {
        Dict exist = null;
        if (StringUtils.isBlank(dict.getId())) {
            exist = dict;
            exist.setId(null);
            exist.setType(getType());
        }
        else {
            exist = entityManager.find(Dict.class, dict.getId());
            BeanUtils.copyProperties(exist, dict, new String[] { "type",
                                                                "deleted" });
        }
        try {
            dict = dictService.save(exist);
            return JsonUtils.succeedMap(dict);
        }
        catch (Exception e) {
            return JsonUtils.failedJson(e.getMessage());
        }
    }
    
    @RequestMapping("/delete.json")
    @ResponseBody
    public Object delete(String id) {
        if (StringUtils.isBlank(id)) {
            return JsonUtils.failedMap("错误的参数！");
        }
        
        try {
            dictService.delete(id);
            return JsonUtils.succeedMap("");
        }
        catch (Exception e) {
            return JsonUtils.failedJson(e.getMessage());
        }
    }
}
